/**
 *
 */
package com.cmcc.awareness.util;


import javax.xml.bind.DatatypeConverter;
import java.math.BigInteger;
import java.nio.ByteBuffer;

public class CommonUtils {
	
	/**
	 * 
	 */
	public static String bytesToHexString(byte[] textBytes){
		return DatatypeConverter.printHexBinary(textBytes);
	}
	
	
	
	public static byte[] loadByte(int length,ByteBuffer byteBuffer) {
		byte[] bytes = new byte[length];
		byteBuffer.get(bytes);
		return bytes;
	}
	
	// XXX 注意!有符号的数字转换可能会出错
	public static BigInteger toBigInteger(byte[] arr) {
		// 在原数组前插入一字节作为符号位
		byte[] result = new byte[arr.length + 1];
		for (int i = arr.length; i > 0; i--) {
			result[i] = arr[i - 1];
		}
		return new BigInteger(result);
	}
	
	/**
	 * 反转byte数组
	 * @param oldBytes
	 * @return
	 */
	public static byte[] reverseBytes(byte[] oldBytes){
		byte[] newBytes =  new byte[oldBytes.length];
		for(int i=0 ;i<oldBytes.length ; i++){
			newBytes[i] = oldBytes[oldBytes.length - i -1];
		}
		return newBytes;
	}
	
	/**
	 * 数组拼接
	 * @param data1
	 * @param data2
	 * @return
	 */
	public static byte[] jointBytes(byte[] data1, byte[] data2) {  
	    byte[] data3 = new byte[data1.length + data2.length];  
	    System.arraycopy(data1, 0, data3, 0, data1.length);  
	    System.arraycopy(data2, 0, data3, data1.length, data2.length);  
	    return data3;  
	} 
	
	/**
	 * 数组转整形
	 */
	//Integer.parseInt(DatatypeConverter.printHexBinary(此处为byte[]), 16);
	
	/**
	 * convert byte[] to int  对于byte：0x80000000会报错，7FFFFFFF不会
	 * @param bytes
	 * @return
	 */
	public static int bytesToInt(byte[] bytes){
		String bytesStr = bytesToStringByBit(bytes);
		Integer bytesInteger = Integer.valueOf(bytesStr,2);
		return bytesInteger;
	}
	/**
	 * byte[] convert to String by bit
	 * 
	 * @param bytes
	 * @return
	 */
	public static String bytesToStringByBit(byte[] bytes){
		StringBuffer bytesStr = new StringBuffer();
		for( byte b : bytes ){
			bytesStr.append(byteToStringByBit(b));
		}
		return bytesStr.toString();
	}
	/**
	 * byte convert to String by bit
	 * 返回单字节每一位的实际情况
	 * @param b
	 * @return
	 */
	public static String byteToStringByBit(byte b){
		StringBuffer sb = new StringBuffer();
		for (int i = 7; i >= 0; i--) {
			String bitStr = Byte.toString((byte) (b >> i & 1));
            sb.append(bitStr);
        }
		return sb.toString();
	}
	
	public static String byteToHexString(byte b) {
		String hexStr = Integer.toHexString(b & 0xFF);
		if (hexStr.length() == 1) {
			return "0" + hexStr;
		} else {
			return hexStr;
		}
	}

}
